package com.orhon.smartcampus.basicComponents.service;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;

import javax.annotation.PostConstruct;

import org.hibernate.HibernateException;
import org.hibernate.Query;
import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.orm.hibernate4.HibernateCallback;
import org.springframework.orm.hibernate4.HibernateTemplate;
import org.springframework.stereotype.Component;
import org.springframework.transaction.annotation.Transactional;

import com.google.common.base.Optional;
import com.orhon.smartcampus.basicComponents.GQLLang;
import com.orhon.smartcampus.modules.base.gqlModel.GQLDictionary;
import com.orhon.smartcampus.modules.base.gqlModel.GQLRegion;

@Component
public class GQLUtil {

	@Autowired
	private SessionFactory sessionFactory;
	private static SessionFactory statisSessionFactory;

	@Autowired
	private HibernateTemplate hibernateTemplate;
	private static HibernateTemplate statichibernateTemplate;

	@PostConstruct
	public void init(){
		statisSessionFactory = sessionFactory;
		statichibernateTemplate = hibernateTemplate;
	}	
	public static GQLRegion Region (HashMap<String,Object> item) {
		GQLRegion gqlregion = new GQLRegion();
		if(item!=null&&item.size()>0) {
			gqlregion.setId(Long.valueOf(item.get("id").toString()));
			gqlregion.setSlug((String)item.get("region_slug"));
			gqlregion.setLevel((Integer)item.get("level"));
			gqlregion.setOrder((Integer)item.get("region_order"));
			gqlregion.setCreated_at(DateService.convertDbDate(item.get("created_at")));
			gqlregion.setUpdated_at(DateService.convertDbDate(item.get("created_at")));
			gqlregion.setDeleted_at(DateService.convertDbDate(item.get("created_at")));
			gqlregion.setName(Lang(item.get("region_name").toString()));
		}
		return gqlregion;
	}
	/**
	 * 数据字典
	 */

	public static GQLDictionary getDictionary(HashMap<String, Object> item){
		GQLDictionary dictionary = new GQLDictionary();
		if(item!=null) {
			dictionary.setId(Long.parseLong(item.get("id").toString()));
			dictionary.setParent_id(Long.parseLong(item.get("parent_id").toString()));
			dictionary.setAlias((String)item.get("alias"));
			dictionary.setType((String)item.get("type"));
			dictionary.setName(Lang(item.get("dictionary_name").toString()));
			dictionary.setDescription(Lang(item.get("dictionary_description").toString()));
			//dictionary.setStatus(item.get("status"));
			dictionary.setMeta(Lang(item.get("meta")));
			dictionary.setValue((String)item.get("dictionary_value"));	
		}
		return dictionary;
	}

    @Transactional
	public static List findPage(final String hql ,final int page ,final int pageSize){
		List list = (List)statichibernateTemplate.execute(new HibernateCallback(){public Object doInHibernate(Session session)
				throws HibernateException {
			String hql1 = "from "+hql;
			Query query = session.createQuery(hql1);
			if(pageSize==0) {
				return query.list();
			}else {
				int begin = (page-1)*pageSize;
				query.setFirstResult(begin);
				query.setMaxResults(pageSize);
				return query.list();
			}
		}});
		return list;
	}
    @Transactional
	public static List findIds(final String hql,String ids){
		List list = (List)statichibernateTemplate.execute(new HibernateCallback(){public Object doInHibernate(Session session)
				throws HibernateException {
			String hql1 = "from "+hql;
			Query query = session.createQuery(hql1);
			query.setParameter("id", ids);
			return query.list();

		}});
		return list;
	}
    @Transactional
	public static Object findObject(final String hql){
		Object obj = statichibernateTemplate.execute(new HibernateCallback(){
			public Object doInHibernate(Session session)
					throws HibernateException {
				String hql1 = "from "+hql;
				Query query = session.createQuery(hql1);
				List list = query.list();
				if(list.size()>0&&list!=null) {
					return list.get(0);
				}else {
					return null;
				}
			}});
		return obj;
	}

    @Transactional
	public static int total(final String hql){
		//利用HibernateTemplate.execute()方法，以回调方式使用,不需要关闭session
		String total = (String)statichibernateTemplate.execute(new HibernateCallback(){
			public Object doInHibernate(Session session)
					throws HibernateException {
				String hql1 = "select count(*) from  "+hql;
				Query query = session.createQuery(hql1);
				return  query.list().get(0).toString();
			}});
		return Integer.parseInt(total);
	}

	public static GQLLang Lang(Object item) {
		if(item ==null || item.equals(null)) {
			return null;
		}
		Optional<String> a = Optional.of(((String)item) );
		GQLLang b = new GQLLang(a.or("{}"));
		return b;

	}

	public static List StringToList(String ids) {
		if(ids==null) {
			return null;
		}
		String substring = ids.substring(1, ids.length()-1);
		if(substring.split(",").length >0 || !substring.equals(null)) {
			ArrayList list = new ArrayList(); 
			String[] id = substring.split(",");
			for (String string : id) {
				try {
					int i = Integer.parseInt(string);
					list.add(string);
				} catch (Exception e) {
					String string2 = string.substring(1, string.length()-1);
					list.add(string2);
				}
			}
			return list;
		}
		return null;


	}
}
